# coding:utf-8

from config import app
from const import BorrowCardApplyStatus
from permission_control import is_common_user, is_sys_admin, get_current_role
from db.models import User
from flask_login import LoginManager, current_user
from flask import redirect, url_for
from cronjob import run_scheduler_job, scheduler
from filters import init_filters
from auth.views import auth_blueprint
from user.user_manage import user_blueprint
from book.book_manage import book_blueprint
from borrow_book.user_borrow import borrow_blueprint
from borrow_book.user_return import return_blueprint
from borrow_book.borrow_manage import borrow_manage_blueprint
from borrow_card.user_card import borrow_card_blueprint
from borrow_card.card_manage import borrow_card_approval_blueprint
from log import logger

login_manager = LoginManager()
login_manager.init_app(app)
init_filters()

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.context_processor
def inject_is_common_user():
    return dict(
        is_common_user=is_common_user,
        is_sys_admin=is_sys_admin,
        get_current_role=get_current_role,
        current_user=current_user,
        BorrowCardApplyStatus=BorrowCardApplyStatus,
                )

@app.route('/')
def index():
    return redirect(url_for('auth.login'))

@app.route('/scheduler-status')
def scheduler_status():
    jobs = scheduler.get_jobs()
    job_info = [str(job) for job in jobs]
    return f"Scheduler has {len(jobs)} job(s): {', '.join(job_info)}"
# login_manager = LoginManager(app)
app.register_blueprint(auth_blueprint, url_prefix='/libary')
app.register_blueprint(user_blueprint, url_prefix='/libary/admin')
app.register_blueprint(book_blueprint, url_prefix='/libary/admin')
app.register_blueprint(borrow_blueprint, url_prefix='/libary')
app.register_blueprint(return_blueprint, url_prefix='/libary')
app.register_blueprint(borrow_manage_blueprint, url_prefix='/libary/admin')
app.register_blueprint(borrow_card_blueprint, url_prefix='/libary')
app.register_blueprint(borrow_card_approval_blueprint, url_prefix='/libary/admin')
print(app.url_map)

if __name__ == '__main__':
    # run_scheduler_job()
    if scheduler.state == 0 :
        scheduler.start()
    app.run(host='0.0.0.0', port=5000, debug=True)